package com.gonsin.ta.logic.parse.condition;

import com.gonsin.ta.logic.enums.ConditionTypeEnum;
import com.gonsin.ta.logic.parse.condition.context.ChainContextImpl;
import com.gonsin.ta.logic.parse.serialize.RunConditionSerial;
import com.gonsin.ta.logic.parse.serialize.SerializeContext;
import com.gonsin.ta.logic.parse.serialize.TaDeserializable;
import com.gonsin.ta.logic.parse.serialize.TaSerializable;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 可运行的 RUN
 */
public class RunCondition extends Condition{

    private List<Executable> executableList = new ArrayList<>();

    private ConditionTypeEnum conditionType;

    public List<Executable> getExecutableList() {
        return executableList;
    }

    public RunCondition(){
        conditionType = ConditionTypeEnum.RUN;
    }

    @Override
    public void execute(ChainContextImpl context) throws Exception {
        for (Executable executableItem : this.getExecutableList()) {
            executableItem.execute(context);
        }
    }

    @Override
    public TaDeserializable toSerializable(SerializeContext serializeContext) {
        RunConditionSerial runCondition = new RunConditionSerial();
        runCondition.setConditionId(getConditionId());
        for(Executable taSerializable : executableList){
            if(taSerializable instanceof TaSerializable){
                runCondition.getExecutableList().add(((TaSerializable) taSerializable).toSerializable(serializeContext));
                continue;
            }
        }
        return runCondition;
    }

    /**
     * 添加可执行单元
     */
    public void addExecutable(Executable executable) {
        executableList.add(executable);
    }

    public ConditionTypeEnum getConditionType() {
        return conditionType;
    }

    @Override
    public List<FutureCondition> searchFutureConditions() {
        List<FutureCondition> conditions = new ArrayList<>();
        for(Executable executable : executableList){
            if(executable instanceof FutureCondition){
                conditions.add((FutureCondition) executable);
                continue;
            }
            if(executable instanceof Condition){
                List<FutureCondition> childConditions = ((Condition)executable).searchFutureConditions();
                if(!CollectionUtils.isEmpty(childConditions)){
                    conditions.addAll(childConditions);
                }
            }
        }
        return conditions;
    }
}
